<template>
  <el-dialog
    :visible.sync="visible"
    width="95%"
    v-if="visible"
    :close-on-click-modal="false"
    :modal="true"
    :destroy-on-close="true"
    :before-close="cancelReport"
    :title="widgetName ? widgetName : 'Drill Through'"
    append-to-body
  >
    <div style="height: auto;min-height: 40px;border-radius: 2px;">
        <el-button size="mini" plain type="primary" @click="commandClick('chuliao',widgetName.split(':')[1])">出料</el-button>
        <el-button size="mini" plain type="primary" @click="commandClick('shangliao',widgetName.split(':')[1])">上料</el-button>
        <el-button size="mini" plain type="primary" @click="clickSelect(widgetName.split(':')[1])">入库</el-button>
    </div> 
    <div v-loading="loading" class="drill-through-dialog-class">
      <ejs-grid
        v-if="comDataList.length > 0"
        :dataSource="comDataList"
        :pdfQueryCellInfo="exportQueryCellInfo"
        :queryCellInfo="customiseCell"
        :allowResizing="gadgetSetting.allowResizing"
        :allowFiltering="gadgetSetting.allowFiltering"
        :filterSettings="gadgetSetting.filterSettings"
        :allowGrouping="gadgetSetting.allowGrouping"
        :allowPaging="gadgetSetting.allowPaging"
        :toolbar="gadgetSetting.toolbar"
        :height="gadgetSetting.height"
        :allowTextWrap="gadgetSetting.allowTextWrap"
        :showColumnChooser="gadgetSetting.showColumnChooser"
        :allowReordering="gadgetSetting.allowReordering"
        :allowSorting="gadgetSetting.allowSorting"
        :pageSettings="gadgetSetting.pageSettings"
        ref="datagrid_id"
        :showColumnMenu="gadgetSetting.showColumnMenu"
        :allowExcelExport="gadgetSetting.allowExcelExport"
        :allowPdfExport="gadgetSetting.allowPdfExport"
        :toolbarClick="toolbarClick"
      >
        <e-columns
          v-if="queryObj.selectFields && queryObj.selectFields.length > 0"
        >
          <e-column
            v-for="(columnItem, index) in queryObj.selectFields"
            :field="columnItem.alias"
            :sortComparer="returnSortComparer(columnItem)"
            :key="index"
            :autoFit="true"
            :disableHtmlEncode="false"
            :headerText="columnItem.alias"
          >
          </e-column>         
        </e-columns>
      </ejs-grid>
      <div v-else class="drill-through-class">
        <div class="no_data_box">
          <div class="no_data_img"></div>
          <div class="no_data_text">
            {{ $t('custom.component.gadget.noFound') }}
          </div>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" @click="visible = false">{{
        $t('attribute.close')
      }}</el-button>
    </span>
    <formviewdialog :formViewData="formViewData"
                    :rowDataItem="rowDataItem"
                    ref="formView-dialog"
                    v-if="formViewVisible"></formviewdialog>
  </el-dialog>
</template>

<script>
import Vue from 'vue'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import { hyperLinksTool } from '@/utils/common'
import formviewdialog from '@/components/gadget/crud-form-plus/components/form-view-dialog'
import JsPDF from 'jspdf'
import { getInnerText, getUrl } from '@/components/storybook/utilties/tools'
import moment from 'moment'
import { exportCvs } from '@/utils/exportPdfCvs'
export default {
  mixins: [mixinFormatViewModule],
  components: {formviewdialog},
  props: {
    gadgetId: {
      type: String,
      default: ''
    },
    pageId: {
      type: String,
      default: ''
    },
    drillThrough: {
      type: Object,
      default: () => {}
    },
    widgetName: {
      type: String,
      default: ''
    },
    queryId: {
      type: String,
      default: ''
    },
    slicer: {
      type: Object,
      default: () => {}
    },
    gadgetType: {
      type: String,
      default: ''
    },
    code: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      loading: false,
      isGridInit: false,
      gadgetSetting: {
        showColumnMenu: true,
        allowResizing: true,
        allowFiltering: true,
        filterSettings: { type: 'Excel' },
        allowGrouping: false,
        allowPaging: true,
        allowExcelExport: true,
        allowPdfExport: true,
        toolbar: [
          'PdfExport',
          'CsvExport',
          'Search',
          'ColumnChooser',
          'ExcelExport'
        ], // 'ExcelExport' '导出 Excel']
        showColumnChooser: true,
        groupOptions: { columns: ['name'] },
        allowReordering: true,
        allowSorting: true,
        allowTextWrap: true,
        height: window.innerHeight - 500,
        pageSettings: {
          pageSize: 50,
          pageSizes: [50, 100, 200, 1000],
          pageCount: 4
        },
        groupSettings: {
          allowReordering: false,
          columns: [],
          disablePageWiseAggregates: false,
          enableLazyLoading: false,
          showDropArea: false,
          showGroupedColumn: false,
          showToggleButton: false
        }
      },
      dataList: [],
      selectFieldsList: [],
      queryObj: {},
      originDataList: [],
      formViewVisible: false,
      rowDataItem:{},
      formViewData:{}
    }
  },

  computed: {
    comDataList() {
      var _self = this
      var retdata = []
      retdata = _self.dataList
      return retdata
    }
  },
  watch: {
    drillThrough: {
      handler: function (val) {},
      deep: true
    }
  },
  created() {
    Vue['_this_ltk_drill_through'] = this
  },
  methods: {
    returnSortComparer(item) {
      if (
        item.dbType &&
        (item.dbType === 'datetime' || item.dbType === 'date')
      ) {
        return ''//return this.sortComparerDate
      } else if (item.dbType && item.dbType === 'number') {
        return this.sortComparerNumber
      } else {
        return ''
      }
    },
    sortComparerDate(reference, comparer) {
      let left = new Date(reference.replace(/[a-zA-Z]/g, '')).getTime()
      let right = new Date(comparer.replace(/[a-zA-Z]/g, '')).getTime()
      if (left < right) {
        return -1
      }
      if (left > right) {
        return 1
      }
      return 0
    },
    sortComparerNumber(reference, comparer) {
      // eslint-disable-next-line no-useless-escape
      let left = reference
        ? Number(
            reference
              .toString()
              .replace(/[^0-9,\.-]/gi, '')
              .replace(/\,/g, '')
          )
        : 0
      // eslint-disable-next-line no-useless-escape
      let right = comparer
        ? Number(
            comparer
              .toString()
              .replace(/[^0-9,\.-]/gi, '')
              .replace(/\,/g, '')
          )
        : 0
      if (left < right) {
        return -1
      }
      if (left > right) {
        return 1
      }
      return 0
    },
    init(data) {
      this.visible = true
      this.$nextTick(() => {
        this.query(data)
      })
    },
    cancelReport() {
      this.visible = false
      this.dataList = []
      this.isGridInit = false
    },
    customiseCell(args) {},
    exportQueryCellInfo(args) {
      try {
        let findTypeObj = this.selectFieldsList.find(
          item =>
            item.columnName === args.column.foreignKeyField ||
            item.alias === args.column.foreignKeyField
        )
        if (findTypeObj && findTypeObj.businessType === 'hyperlinks') {
          // eslint-disable-next-line
          var pattern = />(.+)</
          let tempValue = args.value
            ? pattern.exec(args.value)[1]
              ? pattern.exec(args.value)[1]
              : ''
            : ''
          args.value = tempValue
          args.data[args.column.foreignKeyField] = tempValue
          let temp = hyperLinksTool(
            tempValue,
            'gridgadget',
            findTypeObj.fieldsFormat,
            args.data,
            this.selectFieldsList
          )

          if (temp) {
            args.hyperLink = {
              target: temp,
              displayText: tempValue
            }
          }
        }
      } catch (error) {}
    },
    dataBound(args) {
      if (!this.isGridInit) {
        this.isGridInit = true
        var _self = this
        if (_self.$refs['datagrid_id']) {
          var element = JSON.parse(
            _self.$refs['datagrid_id'].ej2Instances.getPersistData()
          )
          if (element && element.columns.length > 0) {
            for (let i = 0; i < element.columns.length; i++) {
            // element.columns[i].autoFit = true
              element.columns[i]['disableHtmlEncode'] = false
            }
            _self.$refs['datagrid_id'].ej2Instances.setProperties(element)
          }
        }
      }
    },
    query(data) {
      let _self = this
      _self.loading = true
      if (_self.gadgetType === 'chartgridgadget') {
        const params = {
          code: _self.code,
          gadgetId: _self.gadgetId,
          gadgettype: _self.gadgettype,
          pageId: _self.pageId ? _self.pageId : '',
          slicer: { ..._self.slicer },
          type: 'widget',
          widgetName: _self.widgetName
        }
        _self.dataList = []
        _self.originDataList = []
        this.$interface.reports
          .getReportDataInfo(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            data = null
            _self.selectFieldsList = res.query.selectFields
              ? res.query.selectFields
              : []
            _self.originDataList = res.data
            _self.dataList = _self.setFormatFunctionForDrillThrough(
              res.data,
              _self.selectFieldsList
            )
            try {
              _self.dataList.forEach(item => {
                for (var key in item) {
                  let field = _self.selectFieldsList.find(i => i.alias === key)
                  if (field) {
                    if (field.dbType === 'number') {
                      if (!item[key]) {
                        item[key] = 0
                      }
                    }
                  }
                }
              })
            } catch (error) {}
            _self.queryObj = res.query
            _self.isGridInit = false
            _self.loading = false
          })
          .catch(() => {
            _self.loading = false
          })
      } else {
        const params = {
          slicer: { ..._self.slicer },
          gadgetId: _self.gadgetId,
          pageId: _self.pageId ? _self.pageId : '',
          drillThrough: data || '', // "'story_points' = 'undefined'",
          showQuery: true,
          queryId: _self.queryId || ''
        }
        _self.dataList = []
        _self.originDataList = []
        this.$interface.reports
          .postInfoForGetDataApi(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            data = null
            _self.selectFieldsList = res.query.selectFields
              ? res.query.selectFields
              : []
            _self.originDataList = res.data
            _self.dataList = _self.setFormatFunctionForDrillThrough(
              res.data,
              _self.selectFieldsList
            )
            try {
              _self.dataList.forEach(item => {
                for (var key in item) {
                  let field = _self.selectFieldsList.find(i => i.alias === key)
                  if (field) {
                    if (field.dbType === 'number') {
                      if (!item[key]) {
                        item[key] = 0
                      }
                    }
                  }
                }
              })
            } catch (error) {}
            _self.queryObj = res.query
            _self.isGridInit = false
            _self.loading = false
          })
          .catch(() => {
            _self.loading = false
          })
      }
    },
    toolbarClick(args) {
      var excelExportProperties = {}
      switch (args.item.text) {
        case 'PDF Export':
          const head = this.queryObj.selectFields || []
          const linkIndex = head.findIndex(i => i.businessType === 'hyperlinks')
          const doc = new JsPDF()
          const body = this.dataList.map(record => {
            for (let key in record) {
              if (linkIndex !== -1 && head[linkIndex].alias === key) {
                record.iUrl = getUrl(record[key])
                record.iText = getInnerText(record[key])
              }
            }
            return record
          })

          const columns = head.map(i => ({
            ...i,
            header: i.alias,
            dataKey:
              linkIndex !== -1 && head[linkIndex].alias === i.alias
                ? 'iText'
                : i.alias
          }))
          doc.autoTable({
            columns,
            body,
            horizontalPageBreak: true,
            styles: { overflow: 'ellipsize', cellWidth: 'wrap' },
            columnStyles: { text: { cellWidth: 'auto' } },
            willDrawCell: data => {
              if (data.column.raw.businessType === 'hyperlinks') {
                const { iUrl, iText } = data.row.raw
                data.cell.text = [iText]

                doc.link(
                  data.cell.x,
                  data.cell.y,
                  data.cell.width,
                  data.cell.height,
                  { url: iUrl }
                )
              }
            }
          })
          doc.save('Export.pdf')

          // this.$refs['datagrid_id'].pdfExport(data)
          break
        case '导出 Excel':
          (this.$refs['datagrid_id']).excelExport()
          break
        case 'Excel Export':
          this.dataList.forEach(item => {
            for (var key in item) {
              if (item[key] && item[key].toString().includes('<a')) {
                item[key] = item[key].replace(/[a-zA-z]+:\/\/[\S]*/, val => {
                  if (val[val.length - 1] === '"') {
                    val = val.slice(0, val.length - 1)
                  }
                  // eslint-disable-next-line
                  let temp = encodeURIComponent(val) + '"'
                  return temp
                })
              }
            }
          })
          excelExportProperties = {
            dataSource: this.dataList
          }
          this.$refs['datagrid_id'].excelExport(excelExportProperties)
          break
        case 'CSV Export':
          exportCvs(this.dataList, this.selectFieldsList)
          break
      }
    },
    replaceString (str, row) {
      const reg = /\{(.*?)\}/g;
      if (reg.test(str)) {
        const regex = /\{(.*?)\}/;
        let field = str.match(regex);
        if (row) {
          if (!row[field[1]]) {
            this.$message.error(`${field[1]} field not found`)
            return str
          }
          str = str.replace(reg, row[field[1]])
        }
      }
      return str
    },
    clickSelect(site){
      this.rowDataItem = {
        stereoscopic_row:site.split('-')[0],
        stereoscopic_line:site.split('-')[1],
        stereoscopic_tier:site.split('-')[2],
        stereoscopic_site:site
      }
      this.formViewData = {
        formCode: '1522829948463747072',
        formKey: '',
        dataFrom: 'rowdata', 
        action: '',
        saveCondition:  null
      }
      this.formViewVisible = true
        this.$nextTick(() => {        
          this.$refs['formView-dialog'].visible = true
        })
    },
    commandClick (type,site) {
      let data = {
          'api': {
            'url': '/web/ddj/add/command',
            'method': 'POST',
            'params': {
              "lgber":"1",
              "lgnum":"1",
              "lgtyp":"1",
              "zsyrl":"100",
              "zzyms":"1",
              "zjxklx":"1",
              "lgpla": site
            }
          }
        }
      if (type === 'chuliao') {
        data.api.params.zsjzl = 2
        this.apiRequest(data)
      }
      if (type === 'shangliao') {
        data.api.params.zsjzl = 1
        this.apiRequest(data)
      }
    },
    apiRequest (data) {
      let params = {}
      params = this.replaceString(data.api.params)
      let url = this.replaceString(data.api.url)
      this.$interface.customRequest(data.api.method, url, params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        return this.$message.success(res.msg)
      })
    },
  },
  destroyed() {
    delete Vue['_this_ltk_drill_through']
  },
  remove() {
    this.close()
    if (this.drop.parentNode) {
      this.drop.parentNode.removeChild(this.drop)
    }
  }
}
</script>

<style lang="scss">
.assa {
  color: red;
}
.more_text_drill {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.drill-through-class {
  height: 45vh;
  .no_data_box {
    margin-top: 150px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .no_data_img {
      width: 164px;
      height: 99px;
      margin-bottom: 5px;
      background-image: url('#{$--ossLink}/app/view_pageheader/dataset_nodate.png');
      background-repeat: no-repeat;
      background-size: 164px 99px;
      background-position: center;
    }
    .no_data_text {
      margin-bottom: 10px;
      height: 20px;
      font-size: 14px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.5);
      line-height: 20px;
    }
    .no_data_intro {
      width: 200px;
      height: 34px;
      font-size: 12px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.25);
      line-height: 17px;
      text-align: center;
    }
  }
}
.drill-through-dialog-class {
  .e-grid .e-content {
    height: 45vh !important;
  }
}
</style>
